
import unittest
import feature
import featureindex

TEST_FEATURES = 'test.bowtie_sorted_summary.txt'
TEST_INDEX = 'test.bowtie_sorted_summary.INDEX'
TEST_BAD_INDEX = 'test.bowtie_sorted_summary.corrupted.INDEX'
TEST_COVERAGE_INDEX = 'test.coverage_summary.INDEX'

class FeatureTests(unittest.TestCase):

    def setUp(self):
        self.index = featureindex.FeatureIndex()

    def testcreate(self):
        '''Test creation of an index from a sorted summary file.'''
        self.index.createFromFeatures(TEST_FEATURES)
        self.assertFalse(self.index.validationError())

    def testload(self):
        '''Test loading of a pre-built index.'''
        self.index.loadIndex(TEST_INDEX)
        self.assertFalse(self.index.validationError())

    def testvalidation(self):
        '''Test failed validation of a corrupted index.'''
        self.index.loadIndex(TEST_BAD_INDEX)
        self.assertTrue(self.index.validationError())
        
    def testgetfeatures(self):
        '''Test selection of features from index.'''
        features = list(featureindex.getFeatures(TEST_INDEX, ("chr1", 1600000, 1700000)))
        self.assertEqual(len(features), 388)
        self.assertEqual(features[-1].epos, 1699209L)
        self.assertEqual(sum([f.spos for f in features]), 638682805L)

    def testgetcoverage(self):
        '''Test calculation of expression from indexed coverage.'''
        features = list(featureindex.getFeatures(TEST_COVERAGE_INDEX, ("chr1", 0, 1000000000)))
        sm = 0
        smsqr = 0
        for feature in features:
            reads = feature.getDetails().reads
            sm += reads
            smsqr += reads*reads
        self.assertEqual(sm, 669776)
        self.assertEqual(smsqr, 132365198)
        
    def tearDown(self):
        pass

def suite():
    return unittest.TestLoader().loadTestsFromTestCase(FeatureTests)

if __name__=='__main__':
    suite = suite()
    unittest.TextTestRunner(verbosity=3).run(suite)
